package com.example.python_manager.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @Description 动态脚本执行工具
 * @Author lihw
 * @Date 2023/12/27 15:42
 */
@Slf4j
public class ScriptUtil {

    /**
     * 脚本执行工具类
     *      示例: python xxx.py
     *          前置命令为: python
     *          后置命令为空.
     * @param content       脚本内容
     * @param prefixCommand    前置命令     [在脚本前面的命令]
     * @param suffixCommand     后置命令    [在脚本后面的命令]
     * @param fileSuffix    生成脚本临时文件的后缀: js / python
     *
     */
    public Object runScriptString(String content, String[] prefixCommand, String[] suffixCommand, String fileSuffix) throws IOException {
        Path tempFilePath = null;
        BufferedReader reader = null;

        try {
            String pathPrefix = System.getProperty("user.dir");
            Path dirPath = Paths.get(pathPrefix, "script");
            tempFilePath = dirPath.resolve("dynamicScript" + UUID.randomUUID() + "." + fileSuffix);
            if (Files.notExists(dirPath)) {
                Files.createDirectories(dirPath);
            }
            Files.deleteIfExists(tempFilePath);
            Files.createFile(tempFilePath);
            log.info("动态脚本文件路径: {}", tempFilePath);
            Files.writeString(tempFilePath, content);

            List<String> scriptParam = new ArrayList<>();
            scriptParam.addAll(Arrays.asList(prefixCommand));
            scriptParam.add(tempFilePath.toString());
            scriptParam.addAll(Arrays.asList(suffixCommand));

            String[] scriptParamArray = scriptParam.toArray(new String[0]);

            ProcessBuilder processBuilder = new ProcessBuilder(scriptParamArray);
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();

            reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
            String line;
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                // 处理错误情况
                throw new RuntimeException("脚本执行异常");
            }

            String result = output.toString();
            log.info("result: {}", result);

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            // 处理错误情况
            throw new RuntimeException("脚本执行异常");
        } finally {

            // 清理临时文件
            if (tempFilePath != null) {
                try {
                    Files.deleteIfExists(tempFilePath);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (reader != null) {
                reader.close();
            }
        }

    }
}
